<template>
  <div class="p-4">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-4">
      <h1 class="text-2xl font-bold text-slate-800 ">抓取日志</h1>
      <div class="flex gap-2">
        <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="reload">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <el-card shadow="never" class="mb-4">
      <el-form :model="query" inline>
        <el-form-item label="RSS源">
          <el-select v-model="query.rssFeedId" placeholder="选择RSS源" clearable style="width: 200px">
            <el-option
              v-for="feed in rssFeeds"
              :key="feed.id"
              :label="feed.name"
              :value="feed.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="选择状态" clearable style="width: 150px">
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
            <el-option label="部分成功" value="partial_success" />
            <el-option label="超时" value="timeout" />
            <el-option label="网络错误" value="network_error" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 300px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column prop="rssFeedId" label="RSS源" width="150">
          <template #default="{ row }">
            {{ getRssFeedName(row.rssFeedId) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="fetchTime" label="抓取时间" width="180">
          <template #header>
            <div class="flex items-center cursor-pointer hover:text-blue-500 transition-colors" @click="toggleFetchTimeSort">
              <span>抓取时间</span>
              <div class="ml-2 text-lg font-bold">
                <span v-if="query.sortField === 'fetchTime'">
                  <span v-if="query.sortOrder === 'asc'" class="text-blue-500">↑</span>
                  <span v-else class="text-blue-500">↓</span>
                </span>
                <span v-else class="text-gray-400">↕</span>
              </div>
            </div>
          </template>
          <template #default="{ row }">
            {{ formatDateTime(row.fetchTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="totalFetched" label="总抓取" width="100" />
        
        <el-table-column prop="duplicateCount" label="重复数" width="100" />
        
        <el-table-column prop="cleanedCount" label="清洗后" width="100" />
        
        <el-table-column prop="savedCount" label="保存数" width="100" />
        
        <el-table-column label="保存率" width="100">
          <template #default="{ row }">
            <span v-if="row.totalFetched && row.totalFetched > 0">
              {{ ((row.savedCount || 0) / row.totalFetched * 100).toFixed(1) }}%
            </span>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="executionTime" label="执行时间" width="120">
          <template #default="{ row }">
            {{ formatExecutionTime(row.executionTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              <el-icon><View /></el-icon>
              查看详情
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-between items-center mt-4">
        <div class="text-slate-500">
          共 {{ total }} 条记录，当前第 {{ currentPage }} 页
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="抓取日志详情"
      width="900px"
      :close-on-click-modal="false"
      class="fetch-log-detail-dialog"
    >
      <div v-if="currentDetail" class="detail-content">
        <!-- 头部信息卡片 -->
        <el-card class="mb-4" shadow="never">
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
              <div class="text-2xl font-bold text-gray-800">#{{ currentDetail.id }}</div>
              <div>
                <div class="text-lg font-medium text-gray-900">{{ getRssFeedName(currentDetail.rssFeedId) }}</div>
                <div class="text-sm text-gray-500">{{ formatDateTime(currentDetail.fetchTime) }}</div>
              </div>
            </div>
            <div class="text-right">
              <el-tag :type="getStatusType(currentDetail.status)" size="large">
                {{ getStatusText(currentDetail.status) }}
              </el-tag>
              <div class="text-sm text-gray-500 mt-1">{{ formatExecutionTime(currentDetail.executionTime) }}</div>
            </div>
          </div>
        </el-card>

        <!-- 统计信息网格 -->
        <div class="grid grid-cols-4 gap-4 mb-6">
          <el-card shadow="never" class="stat-card">
            <div class="text-center">
              <div class="text-2xl font-bold text-blue-600">{{ currentDetail.totalFetched || 0 }}</div>
              <div class="text-sm text-gray-600">总抓取</div>
            </div>
          </el-card>
          <el-card shadow="never" class="stat-card">
            <div class="text-center">
              <div class="text-2xl font-bold text-orange-600">{{ currentDetail.duplicateCount || 0 }}</div>
              <div class="text-sm text-gray-600">重复数</div>
            </div>
          </el-card>
          <el-card shadow="never" class="stat-card">
            <div class="text-center">
              <div class="text-2xl font-bold text-green-600">{{ currentDetail.savedCount || 0 }}</div>
              <div class="text-sm text-gray-600">保存数</div>
            </div>
          </el-card>
          <el-card shadow="never" class="stat-card">
            <div class="text-center">
              <div class="text-2xl font-bold text-purple-600">
                <span v-if="currentDetail.totalFetched && currentDetail.totalFetched > 0">
                  {{ ((currentDetail.savedCount || 0) / currentDetail.totalFetched * 100).toFixed(1) }}%
                </span>
                <span v-else class="text-gray-400">-</span>
              </div>
              <div class="text-sm text-gray-600">保存率</div>
            </div>
          </el-card>
        </div>

        <!-- 详细信息表格 -->
        <el-card shadow="never" class="mb-4">
          <template #header>
            <div class="flex items-center">
              <el-icon class="mr-2"><InfoFilled /></el-icon>
              <span>详细信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="抓取日期">{{ currentDetail.fetchDate }}</el-descriptions-item>
            <el-descriptions-item label="清洗后数量">{{ currentDetail.cleanedCount || 0 }}</el-descriptions-item>
            <el-descriptions-item label="HTTP状态码">
              <span v-if="currentDetail.httpStatusCode" :class="getHttpStatusClass(currentDetail.httpStatusCode)">
                {{ currentDetail.httpStatusCode }}
              </span>
              <span v-else class="text-gray-400">-</span>
            </el-descriptions-item>
            <el-descriptions-item label="响应大小">{{ formatFileSize(currentDetail.responseSize) }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(currentDetail.createdAt) }}</el-descriptions-item>
            <el-descriptions-item label="新闻数">{{ currentDetail.newsCount || 0 }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 错误信息 -->
        <el-card v-if="currentDetail.errorMessage" shadow="never" class="error-card">
          <template #header>
            <div class="flex items-center">
              <el-icon class="mr-2 text-red-500"><WarningFilled /></el-icon>
              <span class="text-red-600">错误信息</span>
            </div>
          </template>
          <div class="bg-red-50 border border-red-200 rounded-lg p-4">
            <div class="text-red-800 whitespace-pre-wrap">{{ currentDetail.errorMessage }}</div>
          </div>
        </el-card>
      </div>

      <template #footer>
        <div class="flex justify-end">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete, View, InfoFilled, WarningFilled } from '@element-plus/icons-vue'
import { fetchLogAPI, rssFeedAPI } from '@/services/api'

definePageMeta({ layout: 'admin' })

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedIds = ref([])
const rssFeeds = ref([])
const dateRange = ref([])
const rssFeedNames = ref({}) // RSS源名称映射
const detailDialogVisible = ref(false)
const currentDetail = ref(null)

// 查询条件
const query = reactive({
  rssFeedId: undefined,
  status: undefined,
  startDate: undefined,
  endDate: undefined,
  sortField: 'fetchTime',
  sortOrder: 'desc'
})

// 监听日期范围变化
const updateDateRange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    query.startDate = dateRange.value[0]
    query.endDate = dateRange.value[1]
  } else {
    query.startDate = undefined
    query.endDate = undefined
  }
}

// 加载RSS源列表
const loadRssFeeds = async () => {
  try {
    const data = await rssFeedAPI.getEnabled()
    rssFeeds.value = data || []
  } catch (error) {
    console.error('加载RSS源列表失败:', error)
  }
}

// 加载RSS源名称映射
const loadRssFeedNames = async (feedIds) => {
  if (!feedIds || feedIds.length === 0) return
  
  try {
    const uniqueIds = [...new Set(feedIds)]
    const params = uniqueIds.map(id => `ids=${id}`).join('&')
    const data = await fetchLogAPI.getRssFeedNames(params)
    rssFeedNames.value = { ...rssFeedNames.value, ...data }
  } catch (error) {
    console.error('加载RSS源名称失败:', error)
  }
}

// 获取RSS源名称
const getRssFeedName = (feedId) => {
  return rssFeedNames.value[feedId] || `RSS源${feedId}`
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    updateDateRange()
    const params = {
      ...query,
      page: currentPage.value,
      size: pageSize.value
    }
    
    const data = await fetchLogAPI.getPage(params)
    tableData.value = data.list || []
    total.value = data.total || 0
    
    // 加载RSS源名称
    const feedIds = tableData.value.map(item => item.rssFeedId).filter(id => id)
    await loadRssFeedNames(feedIds)
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(query, {
    rssFeedId: undefined,
    status: undefined,
    startDate: undefined,
    endDate: undefined,
    sortField: 'fetchTime',
    sortOrder: 'desc'
  })
  dateRange.value = []
  currentPage.value = 1
  loadData()
}

// 刷新
const reload = () => {
  loadData()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadData()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 切换抓取时间排序
const toggleFetchTimeSort = () => {
  if (query.sortField === 'fetchTime') {
    // 如果已经是抓取时间排序，则切换升序/降序
    query.sortOrder = query.sortOrder === 'asc' ? 'desc' : 'asc'
  } else {
    // 如果不是抓取时间排序，则设置为抓取时间降序
    query.sortField = 'fetchTime'
    query.sortOrder = 'desc'
  }
  
  currentPage.value = 1
  loadData()
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const data = await fetchLogAPI.getById(row.id)
    currentDetail.value = data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 删除处理
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除ID为 ${row.id} 的抓取日志记录？`, '提示', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    
    await fetchLogAPI.deleteById(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条记录？`, '提示', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    
    await fetchLogAPI.deleteByIds(selectedIds.value)
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 工具函数
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const getStatusType = (status) => {
  const statusMap = {
    'success': 'success',
    'failed': 'danger',
    'partial_success': 'warning',
    'timeout': 'warning',
    'network_error': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'success': '成功',
    'failed': '失败',
    'partial_success': '部分成功',
    'timeout': '超时',
    'network_error': '网络错误'
  }
  return statusMap[status] || status
}

const getHttpStatusClass = (statusCode) => {
  if (statusCode >= 200 && statusCode < 300) return 'text-green-600'
  if (statusCode >= 300 && statusCode < 400) return 'text-blue-600'
  if (statusCode >= 400 && statusCode < 500) return 'text-orange-600'
  if (statusCode >= 500) return 'text-red-600'
  return ''
}

const formatFileSize = (bytes) => {
  if (!bytes) return '-'
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

const formatExecutionTime = (milliseconds) => {
  if (!milliseconds) return '-'
  if (milliseconds < 1000) return `${milliseconds}ms`
  return `${(milliseconds / 1000).toFixed(1)}s`
}

// 初始化
onMounted(() => {
  // 先加载RSS源列表
  loadRssFeeds().then(() => {
    // 再加载数据
    loadData()
  }).catch(error => {
    console.error('初始化失败:', error)
    // 即使RSS源加载失败，也尝试加载数据
    loadData()
  })
})
</script>

<style scoped>
.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 详情弹框样式 */
.fetch-log-detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.stat-card {
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.error-card {
  border-left: 4px solid #f56c6c;
}

.error-card :deep(.el-card__header) {
  background-color: #fef0f0;
  border-bottom: 1px solid #fde2e2;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>


